package com.hethongviet.vending.pages;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Constant;
import com.hethongviet.vending.AppConfig;
import com.hethongviet.vending.R;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.helper.GeneralActivity;
import com.hethongviet.vending.helper.db.AccountSQLite;
import com.hethongviet.vending.helper.db.BoxSQLite;
import com.hethongviet.vending.helper.db.MachineSQLite;
import com.hethongviet.vending.helper.db.ProductSQLite;
import com.hethongviet.vending.helper.dialog.DialogEditDomainName;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.model.Account;
import com.hethongviet.vending.model.Box;
import com.hethongviet.vending.model.MachineInfo;
import com.hethongviet.vending.model.Product;
import com.hethongviet.vending.model.Transaction;
import com.hethongviet.vending.network.CONFIG;
import com.hethongviet.vending.network.CONSTANTS.ACCOUNT;
import com.hethongviet.vending.network.CONSTANTS.PRODUCT;
import com.hethongviet.vending.network.CONSTANTS.SERVICE;
import com.hethongviet.vending.network.CONSTANTS.STATUS;
import com.hethongviet.vending.network.Network;

public class FirstActivity extends GeneralActivity
{
	private boolean _isFirstRun = true;

	private EditText _EditTextMachineCode = null;
	private EditText _EditTextMachineGroupId = null;
	private EditText _EditTextMachineLocationId = null;
	private EditText _EditTextMachineDomainName = null;
	private EditText _EditTextUsername = null;
	private EditText _EditTextPassword = null;

	private CheckBox _CheckBoxIsRent = null;

	private Button _ButtonEditMacAddress = null;
	private Button _ButtonSave = null;
	private Button _ButtonUpdateDate = null;
	private Button _ButtonStart = null;

	private TextView _TextViewMacAddress = null;

	public static final int REQUEST_EDIT_MAC_ADDRESS = 5;

	private MachineInfo _machine = null;

	private AccountSQLite _accountSqLite = null;
	private BoxSQLite _boxSqLite = null;
	private ProductSQLite _productSqLite = null;
	private MachineSQLite _machineSqLite = null;

	public FirstActivity()
	{
		_accountSqLite = new AccountSQLite(this);
		_boxSqLite = new BoxSQLite(this);
		_productSqLite = new ProductSQLite(this);
		_machineSqLite = new MachineSQLite(this);
	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	private void initData()
	{

		// if (!_accountSqLite.isTableExist())
		{
			_accountSqLite.deleteAll();

			_accountSqLite.insert(new Account("0937813357", "Dinh Thi Duyen",
					0, 0, Account.PERMIT_USER, false, "", true,
					System.currentTimeMillis(), "", "duyen", "duyen", 0));

			_accountSqLite.insert(new Account("0942478466", "Dinh Ngoc Tan", 0,
					0, Account.PERMIT_USER, false, "", true,
					System.currentTimeMillis(), "", "bkit05", "ngoctan", 0));

			_accountSqLite.insert(new Account("0975992243", "Dinh Thi Duyen",
					0, 0, Account.PERMIT_USER, false, "", true,
					System.currentTimeMillis(), "", "duyen", "duyen", 0));

			_accountSqLite.insert(new Account("0903946510",
					"Nguyen Chien Thang", 0, 0, Account.PERMIT_ADMIN, false,
					"", true, System.currentTimeMillis(), "", "thang", "thang",
					0));

		}

		// if (!AppMain.getInstance()._machineInfoSqLite.isTableExist())
		{
			_machineSqLite.deleteAll();

			// HTC One V
			MachineInfo machine;
			machine = new MachineInfo("VM002", 40, System.currentTimeMillis(), 0,
					15, 342142142.23423, 0, 234242.23423, "0975075350", "",
					"0975075350", 1, 1, "0975075350", "1C:B0:94:6E:B8:93",
					"00:12:03:09:14:98", "http://localhost", 1234);

			// Galaxy tab
			machine = new MachineInfo("VM002", 40, System.currentTimeMillis(), 0,
					15, 342142142.23423, 0, 234242.23423, "0975075350", "",
					"0975075350", 1, 1, "0975075350", "CC:F9:E8:1A:DB:23",
					"00:12:03:09:14:98", "http://localhost", 1234);

			// LG P350
			machine = new MachineInfo("VM002", 40, System.currentTimeMillis(), 0,
					15, 342142142.23423, 0, 234242.23423, "0975075350", "",
					"0975075350", 1, 1, "0975075350", "5C:17:D3:9B:2E:76",
					"00:12:03:09:14:98", "http://localhost", 1234);

			machine.setUsernameNetwork(CONFIG.NETWORK_USERNAME);
			machine.setPasswordNetwork(CONFIG.NETWORK_PASSWORD);
			_machineSqLite.insert(machine);
		}

		// if (!_productSqLite.isTableExist())
		{
			_productSqLite.deleteAll();

			if (AppConfig.USE_ACCOUNT_MONEY)
			{
				_productSqLite.insert(new Product("PEPSI", "K0", 0, 5000,
						"Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("AQUAFINA", "K1", 0, 5000,
						"Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("STING", "K2", 0, 8000,
						"Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("YELLOW STING", "K3", 0,
						9000, "Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("SEVENUP", "K4", 0, 8000,
						"Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("REVIVE", "K5", 0, 8000,
						"Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("TWISTER", "K6", 0, 9000,
						"Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("MIRINDA CAM", "K7", 0, 8000,
						"Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("MIRINDA XA XI", "K8", 0,
						9000, "Hang chat luong cao", "index.png"));
				_productSqLite.insert(new Product("LIPTON", "K9", 0, 5000,
						"Hang chat luong cao", "index.png"));
			}
			else
			{
				_productSqLite.insert(new Product("52153", "52153", 0, 5000,
						"Endmill 3.0mm, 2Fl, TiAlN Coated", "M.A. FORD"));
				_productSqLite.insert(new Product("52164", "52164", 0, 5000,
						"Endmill 6.0mm, 2Fl, TiAlN Coated", "M.A. FORD"));
				_productSqLite.insert(new Product("52170", "52170", 0, 5000,
						"Endmill 8.0mm, 2Fl, TiAlN Coated", "M.A. FORD"));
				_productSqLite.insert(new Product("52174", "52174", 0, 5000,
						"Endmill 10.0mm, 2Fl, TiAlN Coated", "M.A. FORD"));
				_productSqLite.insert(new Product("52178", "52178", 0, 5000,
						"Endmill 12.0mm, 2Fl, TiAlN Coated", "M.A. FORD"));

				_productSqLite.insert(new Product("CNMG120408FWKC9110",
						"CNMG120408FWKC9110", 0, 5000,
						"Turning insert Wiper, Steel, R0.8", "KENNAMETAL"));
				_productSqLite.insert(new Product("CNMG120408MNKC9110",
						"CNMG120408MNKC9110", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));
				_productSqLite.insert(new Product("CNMG120408MNKC9125",
						"CNMG120408MNKC9125", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));
				_productSqLite.insert(new Product("CNMG120408MNKC9140",
						"CNMG120408MNKC9140", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG120408MSKC5525",
						"CNMG120408MSKC5525", 0, 5000,
						"Turning insert Medium, Super alloy, R0.8",
						"KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG120408RPKC5010",
						"CNMG120408RPKC5010", 0, 5000, "Hang chat luong cao",
						"KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG120412FNKC9110",
						"CNMG120412FNKC9110", 0, 5000,
						"Turining insert Finishing, Steel, R1.2", "KENNAMETAL"));
				_productSqLite.insert(new Product("CNMG120412FWKC9110",
						"CNMG120412FWKC9110", 0, 5000,
						"Turning Insert Wiper, Steel, R1.2", "KENNAMETAL"));
				_productSqLite.insert(new Product("CNMG120412FWKC9125",
						"CNMG120412FWKC9125", 0, 5000,
						"Turning Insert Wiper, Steel, R1.2", "KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG120412MSK313",
						"CNMG120412MSK313", 0, 5000,
						"Turning Insert Medium, Cermet, R1.2", "KENNAMETAL"));
				_productSqLite.insert(new Product("WNMG080408MNKC9110",
						"WNMG080408MNKC9110", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));
				_productSqLite.insert(new Product("WNMG080412MNKC9110",
						"WNMG080412MNKC9110", 0, 5000,
						"Turning insert Medium, Steel, R1.2", "KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG120408MPKC5010",
						"CNMG120408MPKC5010", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));
				_productSqLite.insert(new Product("CNMG120408MPKCM25",
						"CNMG120408MPKCM25", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));
				_productSqLite.insert(new Product("CNMG120408MPKCP25",
						"CNMG120408MPKCP25", 0, 5000,
						"Turning insert Medium, Steel, R1.2", "KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG120412MPKCM25",
						"CNMG120412MPKCM25", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG160408FNKCP25",
						"CNMG160408FNKCP25", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG160608MNKC9110",
						"CNMG160608MNKC9110", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG160612MPKC5010",
						"CNMG160612MPKC5010", 0, 5000,
						"Turning insert Medium, Steel, R1.2", "KENNAMETAL"));
				_productSqLite.insert(new Product("TCMT16T308LFKC5010",
						"TCMT16T308LFKC5010", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));

				_productSqLite.insert(new Product("CNMG160608RPKCP25",
						"CNMG160608RPKCP25", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));
				_productSqLite.insert(new Product("CNMG160608MPKCM25",
						"CNMG160608MPKCM25", 0, 5000,
						"Turning insert Medium, Steel, R0.8", "KENNAMETAL"));
				_productSqLite.insert(new Product("SPGN090304KC5010",
						"SPGN090304KC5010", 0, 5000,
						"Turning insert Medium, Steel, R1.2", "KENNAMETAL"));
				_productSqLite.insert(new Product("TCMT16T303LFKC5025",
						"TCMT16T303LFKC5025", 0, 5000,
						"Turning insert Medium, Steel, R1.2", "KENNAMETAL"));

				_productSqLite.insert(new Product("Vien Bo mau", "DEERVET", 0,
						5000, "", "KENNAMETAL"));
				_productSqLite.insert(new Product("DNMG150404MNKC9125",
						"DNMG150404MNKC9125", 0, 5000, "", "KENNAMETAL"));

				_productSqLite.insert(new Product("TPGT090204LFKC5410",
						"TPGT090204LFKC5410", 0, 5000, "", "KENNAMETAL"));
				_productSqLite.insert(new Product("TPGT110204LFKC5410",
						"TPGT110204LFKC5410", 0, 5000, "", "KENNAMETAL"));
				_productSqLite.insert(new Product("TPUN110304K68",
						"TPUN110304K68", 0, 5000, "", "KENNAMETAL"));
				_productSqLite.insert(new Product("VBMT160408LFKC9110",
						"VBMT160408LFKC9110", 0, 5000, "", "KENNAMETAL"));
				_productSqLite.insert(new Product("VBMT160408LFKC9125",
						"VBMT160408LFKC9125", 0, 5000, "", "KENNAMETAL"));
			}
		}
		// if (!_boxSqLite.isTableExist())
		{
			_boxSqLite.deleteAll();
			
			for (int index = 0; index < Constant.MAX_BOX_AMOUNT - 5; index++)
			{
				_boxSqLite.insert(new Box(index + 1, String.format("%02d", index), "", 0, 0, 0, "", 1));
			}
		}

	}

	@SuppressWarnings("unused")
	private void initData1()
	{

		// if (!_accountSqLite.isTableExist())
		{
			_accountSqLite.deleteAll();

			_accountSqLite.insert(new Account("0937813357", "Dinh Thi Duyen",
					0, 0, Account.PERMIT_USER, false, "", true,
					System.currentTimeMillis(), "", "bkit05", "ngoctan", 0));

			_accountSqLite.insert(new Account("0942478466", "Dinh Ngoc Tan", 0,
					0, Account.PERMIT_USER, false, "", true,
					System.currentTimeMillis(), "", "duyen", "duyen", 0));

			_accountSqLite.insert(new Account("0975992243", "Dinh Thi Duyen",
					0, 0, Account.PERMIT_USER, false, "", true,
					System.currentTimeMillis(), "", "duyen", "duyen", 0));

			_accountSqLite.insert(new Account("0903946510",
					"Nguyen Chien Thang", 0, 0, Account.PERMIT_ADMIN, false,
					"", true, System.currentTimeMillis(), "", "thang", "thang",
					0));

		}
		// if (!AppMain.getInstance()._machineInfoSqLite.isTableExist())
		{
			_machineSqLite.deleteAll();

			// HTC One V
			MachineInfo machine;
			machine = new MachineInfo("VM001", 40, System.currentTimeMillis(), 0,
					15, 342142142.23423, 0, 234242.23423, "0975075350", "",
					"0975075350", 1, 1, "0975075350", "1C:B0:94:6E:B8:93",
					"00:12:03:09:14:98", "http://localhost", 1234);

			// LG P350
			machine = new MachineInfo("VM001", 40, System.currentTimeMillis(), 0,
					15, 342142142.23423, 0, 234242.23423, "0975075350", "",
					"0975075350", 1, 1, "0975075350", "38:EC:E4:BA:E1:33",
					"00:12:03:09:14:98", "http://localhost", 1234);

			// Galaxy tab
			machine = new MachineInfo("VM001", 40, System.currentTimeMillis(), 0,
					15, 342142142.23423, 0, 234242.23423, "0975075350", "",
					"0975075350", 1, 1, "0975075350", "5C:17:D3:9B:2E:76",
					"00:12:03:09:14:98", "http://localhost", 1234);

			machine.setUsernameNetwork(CONFIG.NETWORK_USERNAME);
			machine.setPasswordNetwork(CONFIG.NETWORK_PASSWORD);
			_machineSqLite.insert(machine);
		}

		// if (!_productSqLite.isTableExist())
		{
			_productSqLite.deleteAll();
			_productSqLite.insert(new Product("PEPSI", "K0", 0, 5000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("AQUAFINA", "K1", 0, 5000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("STING", "K2", 0, 8000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("YELLOW STING", "K3", 0, 9000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("SEVENUP", "K4", 0, 8000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("REVIVE", "K5", 0, 8000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("TWISTER", "K6", 0, 9000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("MIRINDA CAM", "K7", 0, 8000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("MIRINDA XA XI", "K8", 0, 9000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("COCA COLA", "K9", 0, 5000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("LAVIE", "K10", 0, 5000,
					"Hang chat luong cao", ""));
			_productSqLite.insert(new Product("C2", "K11", 0, 5000,
					"Hang chat luong cao", ""));
		}
		// if (!_boxSqLite.isTableExist())
		{
			_boxSqLite.deleteAll();

			for (int index = 0; index < Constant.MAX_BOX_AMOUNT; index++)
			{
				_boxSqLite.insert(new Box(index + 1, String.format("%02d", index), "", 0, 0, 0, "", 1));
			}
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.page_first);

		initDatabase();

		if (!AppConfig.USE_FIRST_SCREEN)
		{
			if (_isFirstRun)
			{
				initData();
			}

			_machine = AppMain.getInstance().getMachineInfo();

			Network.setPassword(_machine.getPasswordNetwork());
			Network.setUsername(_machine.getUsernameNetwork());

			startStandbyScreen();

			return;
		}

		if (_isFirstRun)
		{
			_EditTextMachineCode = (EditText) findViewById(R.id.pause_edit_machine_code);
			_EditTextMachineDomainName = (EditText) findViewById(R.id.pause_edit_machine_domain_name);
			_EditTextMachineGroupId = (EditText) findViewById(R.id.pause_edit_machine_group_id);
			_EditTextMachineLocationId = (EditText) findViewById(R.id.pause_edit_machine_location_id);
			_EditTextUsername = (EditText) findViewById(R.id.pause_edit_machine_username);
			_EditTextPassword = (EditText) findViewById(R.id.pause_edit_machine_password);

			if (AppConfig.IS_DEBUG)
			{
				_EditTextPassword.setText(CONFIG.NETWORK_PASSWORD);
				_EditTextUsername.setText(CONFIG.NETWORK_USERNAME);
			}

			_ButtonEditMacAddress = (Button) findViewById(R.id.pause_button_edit_mac_address);
			_ButtonSave = (Button) findViewById(R.id.pause_button_save);
			_ButtonUpdateDate = (Button) findViewById(R.id.pause_button_update_data);
			_ButtonStart = (Button) findViewById(R.id.pause_button_start);

			_CheckBoxIsRent = (CheckBox) findViewById(R.id.pause_edit_machine_status_rent);

			_TextViewMacAddress = (TextView) findViewById(R.id.pause_machine_bluetooth_serial_mac_address);

			if (_TextViewMacAddress.getText().toString().trim().equals(
					getString(R.string.message_have_no_mac_address)))
			{
				_ButtonEditMacAddress.setText(getString(R.string.config_add));
			}

			_ButtonUpdateDate.setVisibility(View.GONE);
			_ButtonStart.setVisibility(View.GONE);

			_ButtonSave.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{

					/* Get values */

					final String textCode = _EditTextMachineCode.getText().toString();
					if (textCode == null || textCode.equals(""))
					{
						showDialogWithCatch(R.string.input_error_null_machine_code);
						return;
					}

					final String textDomainName = _EditTextMachineDomainName.getText().toString();
					if (textDomainName == null || textDomainName.equals(""))
					{
						showDialogWithCatch(R.string.input_error_null_domain_name);
						return;
					}

					final String textUsername = _EditTextMachineDomainName.getText().toString();
					if (textUsername == null || textUsername.equals(""))
					{
						showDialogWithCatch(R.string.input_error_null_username_server);
						return;
					}

					final String textPassword = _EditTextMachineDomainName.getText().toString();
					if (textPassword == null || textPassword.equals(""))
					{
						showDialogWithCatch(R.string.input_error_null_password_server);
						return;
					}

					final String textGroupId = _EditTextMachineGroupId.getText().toString();
					int groupId = Constant.MACHINE_GROUP_ID;
					try
					{
						groupId = Integer.parseInt(textGroupId);
					} catch (NumberFormatException e)
					{
						e.printStackTrace();
						groupId = Constant.MACHINE_GROUP_ID;
					}

					final String textLocationId = _EditTextMachineLocationId.getText().toString();
					int locationId = Constant.MACHINE_LOCATION_ID;
					try
					{
						locationId = Integer.parseInt(textLocationId);
					} catch (NumberFormatException e)
					{
						e.printStackTrace();
						locationId = Constant.MACHINE_LOCATION_ID;
					}

					final String textMacAddress = _TextViewMacAddress.getText().toString();

					final boolean isRent = _CheckBoxIsRent.isChecked();

					/* Temporary save */
					_machine = new MachineInfo();
					_machine.setAddressPhysicalSerial(textMacAddress);
					_machine.setBoxAmount(Constant.MAX_BOX_AMOUNT);
					_machine.setCode(textCode);
					_machine.setDateCreated(System.currentTimeMillis());
					_machine.setDomainName(textDomainName);
					_machine.setPasswordNetwork(textPassword);
					_machine.setUsernameNetwork(textUsername);
					_machine.setGroupId(groupId);
					_machine.setLocationId(locationId);
					_machine.setStatusRent(isRent ? 1 : 0);
					_machine.setStatus(1);
					if (AppConfig.IS_NETWORK_AVAILABLE)
					{
						// Network.setHost(AppMain.getInstance()._machine.getDomainName());
						Network.setPassword(textPassword);
						Network.setUsername(textUsername);

						/* Send to server to request id */
						showProgress(FirstActivity.this);
						Network.sendMachineInfo(_machine);
					}
				}
			});

			_ButtonEditMacAddress.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{
					String textMacAddress = _TextViewMacAddress.getText().toString();

					// showDialogWithCatch(R.string.config_mac_address);
					Utils.debug(
							"Mac address old = " + textMacAddress);
					Intent intent = new Intent(FirstActivity.this,
							EditMacAddressActivity.class);
					intent.putExtra(EditMacAddressActivity.EXTRA_MAC_ADDRESS,
							textMacAddress);
					startActivityForResult(intent, REQUEST_EDIT_MAC_ADDRESS);
				}
			});

			_ButtonUpdateDate.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{
					isUpdateDataOnline = true;
					updateDataOnline();
					showProgress(FirstActivity.this);
				}
			});

			_ButtonStart.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{
					startStandbyScreen();
				}
			});

		}
		else if (AppConfig.IS_NETWORK_AVAILABLE)
		{
			/* Get data from database */
			if (_machine == null)
			{
				List<MachineInfo> machineInfos = _machineSqLite.getAll();
				if (machineInfos != null && machineInfos.size() != 0)
				{
					_machine = machineInfos.get(0);

					// Network.setHost(AppMain.getInstance()._machine.getDomainName());
					Network.setPassword(_machine.getPasswordNetwork());
					Network.setUsername(_machine.getUsernameNetwork());

					// _LinearLayoutPauseFirstTime.setVisibility(View.GONE);
					startStandbyScreen();
				}
				else
				{
					if (AppConfig.IS_DEBUG)
					{
						Toast.makeText(this,
								"Can not get machine info from database",
								Toast.LENGTH_LONG).show();
					}
					Utils.debug(
							"Can not get machine info from database");

					Intent intent = new Intent(FirstActivity.this,
							PauseActivity.class);
					intent.putExtra(PauseActivity.EXTRA_REQUEST_TYPE,
							Constant.REQUEST_FAIL_LOAD_INFO);
					startActivity(intent);
				}
			}

		}

		if (!AppConfig.IS_NETWORK_AVAILABLE)
		{
			if (_ButtonStart == null)
				_ButtonStart = (Button) findViewById(R.id.pause_button_start);
			_ButtonStart.setVisibility(View.VISIBLE);
			if (_ButtonSave == null)
				_ButtonSave = (Button) findViewById(R.id.pause_button_save);
			_ButtonSave.setVisibility(View.GONE);
			if (_ButtonUpdateDate == null)
				_ButtonUpdateDate = (Button) findViewById(R.id.pause_button_update_data);
			_ButtonUpdateDate.setVisibility(View.GONE);
			_ButtonStart.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View arg0)
				{
					startStandbyScreen();
				}
			});
		}

	}

	private void startStandbyScreen()
	{

		if (AppConfig.AUTO_CREATE_QR_CODE)
		{
			String deviceNumber = AppMain.getInstance().getMachineInfo().getPhoneNumber();

			if (deviceNumber == null || deviceNumber.length() < 5)
			{
				Utils.debug(
						"Error: Device number null or not right!");

				startActivity(new Intent(FirstActivity.this,
						InputDeviceNumberActivity.class));

				return;
			}
		}

		if (AppConfig.IS_BLUETOOTH_ONE_SCREEN)
		{
			startActivity(new Intent(FirstActivity.this,
					StandbyActivityNonBluetooth.class));
		}
		else
		{
			startActivity(new Intent(FirstActivity.this, StandbyActivity.class));
		}
	}

	public void updateMacAddress(String address)
	{
		if (address == null || address.equals(""))
		{
			Utils.debug("Mac address is not change!");
			return;
		}

		String[] strings = address.split("[:]");
		if (strings == null || strings.length != 6)
		{
			Utils.debug("New Mac address is failed load!");
			return;
		}

		Utils.debug("Mac address update = " + address);
		_TextViewMacAddress.setText(address);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_EDIT_MAC_ADDRESS)
		{
			String textMac = null;
			if (data != null)
				textMac = data.getStringExtra(EditMacAddressActivity.EXTRA_MAC_ADDRESS);
			updateMacAddress(textMac);

			_ButtonEditMacAddress.setText(getString(R.string.config_modify));
		}
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.config_domain)
		{
			return new DialogEditDomainName(this, _machine.getDomainName());
		}
		else if (id == R.string.message_error_box_amount_invalid
				|| id == R.string.input_error_null_domain_name
				|| id == R.string.input_error_null_machine_code
				|| id == R.string.input_error_null_password_server
				|| id == R.string.input_error_null_username_server)
		{
			return new DialogMessageBack(this, true,
					R.string.message_error_box_amount_invalid, false);
		}

		else
			return createDialogStatusServer(id);
	}

	private void initDatabase()
	{
		/* Create all table */
		_accountSqLite.open();
		_accountSqLite.close();

		/* This is the first time? */
		List<Box> boxsList = null;
		try
		{
			boxsList = _boxSqLite.getAll();
		} catch (Exception e)
		{
			e.printStackTrace();
			boxsList = null;
		}

		if (boxsList == null || boxsList.size() == 0)
			_isFirstRun = true;
		else
			_isFirstRun = false;
	}

	private boolean isUpdateDataOnline = false;

	private void updateDataOnline()
	{
		if (AppConfig.IS_NETWORK_AVAILABLE)
			Network.sendRequestUpdateAccount();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (KeyEvent.KEYCODE_MENU == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_LEFT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_CENTER == event.getKeyCode()
				|| KeyEvent.KEYCODE_CALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_CAMERA == event.getKeyCode()
				|| KeyEvent.KEYCODE_ENDCALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_HOME == event.getKeyCode()
				|| KeyEvent.KEYCODE_SEARCH == event.getKeyCode()
				|| KeyEvent.KEYCODE_BACK == event.getKeyCode())
		{
			return Utils.disableAllKey(event);
		}
		else
			return super.dispatchKeyEvent(event);

	}

	// @Override
	// public void onAttachedToWindow()
	// {
	// this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
	// super.onAttachedToWindow();
	// }

	@Override
	public void onNetworkMessageIncomming(Transaction transaction)
	{

		if (transaction == null)
		{
			Utils.debug("Null -----------received");
			return;
		}

		String message = transaction.getMessageReceived();
		Utils.debug("Receive message = " + message);

		if (message.equalsIgnoreCase(SERVICE.RESULT_OK))
		{
			Utils.debug("OK!!!!!!!!!!!");
			hideProgressDialog();

			return;
		}

		boolean isOnlyHideProgressDialog = false;
		if (transaction.getMethodSent().equals(SERVICE.GET_ACCOUNTS))
		{
			/* Process data get accounts */
			try
			{
				JSONArray jsonArray = new JSONArray(message);

				for (int i = 0; i < jsonArray.length(); i++)
				{
					JSONObject jsonObjectElement = jsonArray.getJSONObject(i);
					Account account = new Account();

					account.setAmount(jsonObjectElement.getInt(ACCOUNT.COLUMN_INDEX_AMOUNT
							+ ""));
					account.setActive(jsonObjectElement.getInt(ACCOUNT.COLUMN_INDEX_ACTIVE
							+ "") == 1 ? true : false);

					account.setId(jsonObjectElement.getString(
							ACCOUNT.COLUMN_INDEX_USER_NAME + "").trim());

					account.setDateCreated(jsonObjectElement.getLong(ACCOUNT.COLUMN_INDEX_DATE_CREATED
							+ ""));

					account.setGroupId(jsonObjectElement.getInt(ACCOUNT.COLUMN_INDEX_GROUP_ID
							+ ""));

					account.setPassword(jsonObjectElement.getString(ACCOUNT.COLUMN_INDEX_ID
							+ ""));

					account.setPinCode(jsonObjectElement.getString(ACCOUNT.COLUMN_INDEX_PASSWORD
							+ ""));
					account.setPositionId(jsonObjectElement.getInt(ACCOUNT.COLUMN_INDEX_POSITION_ID
							+ ""));

					account.setStaffId(jsonObjectElement.getString(ACCOUNT.COLUMN_INDEX_STAFF_ID
							+ ""));

					account.setTerminated(jsonObjectElement.getInt(ACCOUNT.COLUMN_INDEX_TERMINATED
							+ "") == 1 ? true : false);

					account.setUsername(jsonObjectElement.getString(ACCOUNT.COLUMN_INDEX_USER_NAME
							+ ""));

					_accountSqLite.insert(account);
				}

			} catch (JSONException e1)
			{
				e1.printStackTrace();
			}

			/* Update products if there are request */
			if (isUpdateDataOnline)
			{
				Utils.debug("OK! Getting for products!");
				if (AppConfig.IS_NETWORK_AVAILABLE)
					Network.sendRequestUpdateProduct();
				return;
			}
		}

		if (transaction.getMethodSent().equals(SERVICE.GET_PRODUCTS))
		{
			Utils.debug("Process for products!");
			/* Process data get products */

			try
			{
				JSONArray jsonArray = new JSONArray(message);

				for (int i = 0; i < jsonArray.length(); i++)
				{
					JSONObject jsonObjectElement = jsonArray.getJSONObject(i);
					Product product = new Product();

					// product.setImageName(jsonObjectElement
					// .getString(PRODUCT.COLUMN_INDEX_IMAGE_PATH + ""));

					product.setPrice(jsonObjectElement.getLong(PRODUCT.COLUMN_INDEX_PRICE_SELLING
							+ ""));
					product.setCode(jsonObjectElement.getString(PRODUCT.COLUMN_INDEX_CODE
							+ ""));
					product.setGroupId(jsonObjectElement.getInt(PRODUCT.COLUMN_INDEX_GROUP_ID
							+ ""));
					product.setName(jsonObjectElement.getString(PRODUCT.COLUMN_INDEX_NAME
							+ ""));

					_productSqLite.insert(product);
				}

				runOnUiThread(new Runnable()
				{

					@Override
					public void run()
					{
						_ButtonStart.setVisibility(View.VISIBLE);
						_ButtonSave.setVisibility(View.GONE);
					}
				});

			} catch (JSONException e1)
			{
				e1.printStackTrace();
			}
			Utils.debug("OK!");
		}
		else if (transaction.getMethodSent().equals(SERVICE.UPDATE_MACHINE_INFO))
		{
			Utils.debug("Process for machine info!");
			Utils.debug("value machine = " + message);

			int boxAmount = Constant.MAX_BOX_AMOUNT;

			try
			{
				boxAmount = Integer.parseInt(message);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

			Utils.debug("-------- box amount = " + boxAmount);

			_machine.setBoxAmount(boxAmount);
			_machineSqLite.insert(_machine);

			/* Save box id */
			for (int i = 0; i < boxAmount; i++)
			{
				Box box = new Box();
				box.setName("Box" + (i + 1));
				box.setCommand(addZero(i));
				box.setId(i + 1);
				box.setActive(0);

				_boxSqLite.insert(box);

			}

			isUpdateDataOnline = true;
			updateDataOnline();

		}
		else
		{
			Utils.debug("Unknown type server return!!");
			showDialogWithStatus(STATUS.SERVER_SEND_UNKNOWN_TYPE);
			isOnlyHideProgressDialog = true;
		}

		hideProgressDialog();
		if (!isOnlyHideProgressDialog)
			showDialogWithStatus(STATUS.SERVER_SEND_OK);
	}

	public String addZero(int number)
	{
		if (number < 0)
			return "";
		if (number < 10)
			return "0" + number;
		else
			return "" + number;
	}

	@Override
	public void onConnectFail(int typeError)
	{
		Utils.debug("Connect fail!.......................");
		hideProgressDialog();

		showDialogWithStatus(typeError);
	}

}
